package toy.keli.edic.ui.bookmark.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Divider
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import toy.keli.edic.R
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.PreviewData
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.data.model.Article
import toy.keli.edic.ui.bindkeyBoradEvent
import toy.keli.edic.ui.bookmark.data.BookMark
import toy.keli.edic.ui.home.components.AutoCompleteTextField
import toy.keli.edic.ui.home.viewMode
import toy.keli.edic.ui.listenbook.ListenBookData
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.main.extend.annotatedText
import toy.keli.edic.ui.main.extend.bgRun
import toy.keli.edic.util.ActivityRun
import kotlin.math.max
import kotlin.math.min

val sugSearchResult = arrayListOf<SearchResult>()
@Composable
@Preview(showBackground = true)
fun BookSearch(focusRequester: FocusRequester =FocusRequester(),back:()->Unit={}) {
    val searchResult = remember { mutableStateListOf<SearchResult>() }
    PreviewData.bookSearch(searchResult)
    //键盘下落返回
//    { isOpen ->
//        if (!isOpen && searchResult.size == 0) {
//            back()
//        }
//    }

    Column(modifier = Modifier.padding(15.dp).fillMaxSize().clickable {
        if (searchResult.size == 0) {
            back()
        }
    }) {
        AutoCompleteTextField(
            autoFocus = false,
            requester = focusRequester,
            suggestions = GlobalVal.wordViewModel.suggestions,
            onDoneActionClick = {
                searchResult.addAll(sugSearchResult)
                GlobalVal.wordViewModel.suggestions.value = emptyList()
                bgRun {
                    searchAllArticle(searchResult, it)
                }
            },
            //跳转到
            onItemClick = {
                sugSearchResult.get(this).onClick(it)
                back()
            },
            onClear = {
                newSearchKey = ""
            },
            onCancel = {
                //失去焦点返回
                if (searchResult.size == 0) back()
            }
        ) { key ->
            LaunchedEffect(key) {
                if (key.isNotEmpty())
                    GlobalVal.wordViewModel.prefixMatcher(":" + key, onSugOver = {
                        sugSearchResult.clear()
                        this.value = it.map {
                            val res = SearchResult.fromSearchSug(it)
                            sugSearchResult.add(res)
                            res.name + " : " + res.type.title
                        }
                    })
            }
            Spacer(Modifier.height(50.dp))
            LazyColumn {
                items(searchResult) {
                    Card(modifier = Modifier.clickable {
                        it.onClick(key)
                        back()
                    }
                        .padding(1.dp)
                        .fillMaxWidth()
                    ) {
                        Column(modifier = Modifier.padding(10.dp)) {
                            Row(verticalAlignment = Alignment.Bottom) {
                                Icon(
                                    painter = painterResource(id = it.type.ico),
                                    contentDescription = null,
                                    tint = Color.Unspecified,
                                    modifier = Modifier.size(20.dp)
                                )
                                Spacer(Modifier.width(5.dp))
                                Text(text = annotatedText(it.name, key))
                            }
                            if (it.des.isNotEmpty()) {
                                Divider(
                                    modifier = Modifier.padding(vertical = 1.dp),
                                    color = Color.LightGray, // 分割线颜色
                                    thickness = 1.dp, // 分割线厚度
                                )
                                Row {
                                    Text(
                                        text = it.line.toString()+": ",
                                        fontSize = 10.sp,

                                    )
                                    Text(
                                        text = annotatedText(it.des, key),
                                        fontSize = 10.sp,
                                        color = Color.Gray,
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
enum class SearchType(val ico:Int){
    article(R.drawable.article),
    category(R.drawable.category),
    level(R.drawable.abc_ic_menu_copy_mtrl_am_alpha);

    val title: String?
        get() = mt(name);

    companion object {
        fun byName(s: String): SearchType {
            return values().first{ it.name ==s }
        }
    }
}

class SearchResult(
    val type:SearchType,
    val id:Int,
    val name:String,
    val des:String,
    val line:Int =0,
    val index:Int =0,
){
    fun onClick(key:String){
        when(type){
            SearchType.article -> {
                BookConf.setBook( BookConf(name,id, 0),false)
                viewMode = MenuConf.mode.showArticle
                if(line>0){
                    MainRun(500) {
                        ListenBookData.instance.apply {
                            searchQuery = key
                            searchQueryPos = IntOffset(line, index)
                            dIndex = line
                        }
                    }
                }
            }
            SearchType.category->{
                viewMode = MenuConf.mode.showCategory
                BookMark.changePid(id)
            }
            else ->{
                GlobalVal.wordViewModel.searcher("${type.name}.$id:$name")
            }
        }
    }

    companion object {
        fun fromSearchSug(it: String): SearchResult {
            val a = it.split(Regex("[:\\.]"))
            return SearchResult(type=SearchType.byName(a[0]),id=a[1].toInt(),name=a[2], des ="")
        }
    }
}



var newSearchKey = "";
fun searchAllArticle(result: SnapshotStateList<SearchResult>, s: String) {
    newSearchKey = s
    Article.eachAll{
        if(newSearchKey!=s) return@eachAll
        it.split("\n").forEachIndexed{i,row->
            var start =0;
            var size =0;
            while(true){
                val index = row.indexOf(s,start)
                if (index == -1) break;
                val des = if (row.length > 100) row.substring(max(index - 50,0), min(row.length-1,index + 50)) else row;
                result.add(
                    SearchResult(
                        type = SearchType.article,
                        id = this.id,
                        name = this.name,
                        des = des,
                        line = i,
                        index = size
                    )
                )
                start = index+s.length;
                size++
            }
        }
    }
}